﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;

namespace Landscape.Web.Controls {
    public partial class Playground : System.Web.UI.UserControl {
        private string sessName = typeof(Playground).FullName + "_lastRender";
        protected void Page_Init(object sender, EventArgs e) {
            if (!string.IsNullOrEmpty(Request.QueryString["output"]) && Session[sessName] != null) {
                string dump = (string)Session[sessName];
                Session.Remove(sessName);
                Response.StatusCode = 200;
                Response.ContentType = "text/html";
                Response.Write(dump);
                Response.End();
                return;
            }
        }
        protected void Page_Load(object sender, EventArgs e) {
            txtDataSource.Text = !string.IsNullOrEmpty(txtDataSource.Text) ? txtDataSource.Text : "<root/>";
            if (frmResult.Attributes["src"] != null) frmResult.Attributes.Remove("src");
        }

        protected void btnCompile_Click(object sender, EventArgs e) {
            if (Page.IsValid) {
                try {
                    XmlDocument stylesheet = new XmlDocument();
                    stylesheet.LoadXml(txtStylesheet.Text);
                    XslCompiledTransform xsltCompiled = new XslCompiledTransform();
                    xsltCompiled.Load(stylesheet, new XsltSettings(true, true), null);
                    XPathDocument xdoc;
                    Landscape.Renderer.LoadXPathDocument(txtDataSource.Text, out xdoc);
                    string result = null;
                    using (Stream ms = Landscape.Renderer.XslTransform(xdoc, xsltCompiled, new Dictionary<string, object>())) {
                        using (StreamReader sr = new StreamReader(ms)) {
                            result = sr.ReadToEnd();
                        }
                    }
                    txtResult.Text = result;
                    if(Session[sessName] != null)
                        Session[sessName] = result;
                    else
                        Session.Add(sessName, result);

                    string src = Request.Url.OriginalString;
                    int querypos = src.IndexOf('?');
                    if(querypos > -1){
                        src = src.Insert(querypos + 1, "output=true&");
                    }else{
                        src += "?output=true";
                    }

                    frmResult.Attributes.Add("src", src);
                } catch (Exception ex) {
                    lblMessage.Text = ex.Message;
                    lblMessage.Visible = true;
                }
             
            }
        }
    }
}